import { create } from 'zustand';
import { persist, PersistStorage, StorageValue, redux } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { name } from '../package.json';
import { Draft } from 'immer';
import { ProductInfo } from '@/lib/dianxiaomi';
import { GigaProductDetialInfo } from '@/lib/giga';

const MessageKEY = 'CLSTools-' + 'message-' + name;
export const messageStorage = storage.defineItem<StorageValue<State>>(`local:${MessageKEY}`);

export enum OperationMessageType {
  'success',
  'error',
  'info',
  'verbose',
}

export type OperationMessageData =
  | {
      kind: '产品信息';
      data: ProductInfo;
    }
  | {
      kind: 'GIGA 产品信息';
      data: GigaProductDetialInfo;
    };

export interface OperationMessage {
  type: OperationMessageType;
  // 以货号进行分类
  category: string;
  message: string;
  time?: number;
  data?: OperationMessageData;
  playload?: any;
  id: string;
}

const defaultState = {
  operationMessages: [],
  gigaOperationMessages: [],
};

interface State {
  operationMessages: OperationMessage[];
  gigaOperationMessages: OperationMessage[];
}

type Actions =
  | {
      type: 'reset';
    }
  | {
      type: 'update';
      update: (draftState: Draft<State>) => void;
    };

const persistStorage: PersistStorage<State> = {
  getItem: async () => {
    const state = await messageStorage.getValue();
    if (!state) {
      return {
        state: defaultState,
        version: 0,
      };
    }
    return state;
  },
  setItem: async (key, newValue) => {
    await messageStorage.setValue(newValue);
  },
  removeItem: (): void => {
    messageStorage.removeValue();
  },
};

const reducer = (state: Draft<State>, action: Actions) => {
  if (action.type === 'reset') {
    return defaultState;
  }
  if (action.type === 'update') {
    const update = action.update;
    update(state);
  }
};

export const useMessageStore = create(
  // @ts-expect-error 因为 immer 导致了 reducer 可以返回 undefiend
  persist(immer(redux(reducer, defaultState)), {
    name: MessageKEY,
    storage: persistStorage,
  }),
);
